// pages/oa/application/invoice.js
var api = require("../../../utils/api.js");
import WxValidate from '../../../utils/WxValidate.js'
var orgid = "";
var userId = "";
var util = require('../../../utils/util.js');
var oaId = "";//有值只显示详情
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: [0, 1],
    ticket: ['企业', '个人'],
    billproject: ['律师代理费', '法律顾问费', '咨询费', '法务托管费', '非诉', '其它'],
    billtype: [
      { id: 1, name: '增值税专用发票' },
      { id: 2, name: '增值税普通发票' },
      { id: 3, name: '普通机开发票' }
    ],
    searchName: "",
    case_id: "",//案件id
    costId: "",//案件id
    contract_number: "",//案件号
    plaintiff_collector: "",//委托人
    osApprovalsList: [],//签核人
    accountInfosList: [],//抄送人
    osApprovalsListSize: "",
    userName: "",
    userIds: [],//新增加的抄送人
    examineType: "2",//发票申请
    //附件照片
    fileUrlList: [{}],
    //图片附件
    imgUrls: [""],
    //oa申请数据
    oaApplyInfos: [],
    //显示状态
    showType: "apply",
    //案件详情
    caseInfos: [],
    invoice_project: { "invoice_project": 269 }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    userId = wx.getStorageSync('userId');
    orgid = wx.getStorageSync('companyId');
    oaId = options.oaId;
    var case_id = options.case_id;
    var costId = options.costId;
    var contract_number = options.contract_number;
    this.initValidate();
    var that = this;
    that.setData({
      fileUrlList: new Array(),
      searchName: contract_number,
      costId: costId,
      case_id: case_id
    });
    if (oaId != undefined && oaId != "") {
      //查询该oa申请详情
      that.oaProgressApplyDetail();
    } else {
      that.oaApplyPersonList(true);
    }
  },

  //跳转案件
  chooseCase: function (e) {
    var that = this;
    var searchName = that.data.searchName;
    if (searchName == undefined) {
      searchName = "";
    }
    wx.navigateTo({
      url: "caseList?searchName=" + searchName + "&distribution_case=0&approval_status=0",
    })
  },
  //搜索赋值
  searchName: function (e) {
    this.setData({
      searchName: e.detail.value,
    })
  },
  //查询审核人
  oaApplyPersonList: function (item) {
    var that = this;
    wx.showLoading({
    });
    api.fetchApi2("oaProgress/oaApplyPersonList", {
      orgid: orgid,
      userId: userId,
      examineType: that.data.examineType
    }, "POST").then(res => {
      wx.hideLoading();
      var list = that.data.accountInfosList;
      if (item) {
        list = res.data.accountInfosList;
      }
      that.setData({
        osApprovalsListSize: res.data.osApprovalsList.length,//签核人条数,用于隐藏箭头>
        osApprovalsList: res.data.osApprovalsList,

        accountInfosList: list,

        userName: wx.getStorageSync('name')
      })
    });
  },//查询申请详情
  oaProgressApplyDetail: function () {
    var that = this;
    wx.showLoading({
    });
    api.fetchApi2("myOaApply/oaProgressApplyDetail?oaId=" + oaId + "&examineType=" + that.data.examineType, {
    }, "POST").then(res => {
      wx.hideLoading();
      that.setData({
        osApprovalsListSize: res.data.processPersonList.length,//签核人条数,用于隐藏箭头>
        osApprovalsList: res.data.processPersonList,
        accountInfosList: res.data.accountInfosList,
        oaApplyInfos: res.data.oaApplyInfos,
        caseInfos: res.data.caseInfos,
        fileUrlList: res.data.fileUrlList,
        showType: "showDetail",//显示详情
        oaId: oaId,
      })
    });
  },
  //删除附件
  delImg: function (e) {
    var that = this;
    var url = e.currentTarget.dataset.url;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          var fileUrlList = that.data.fileUrlList;
          var imgUrls = that.data.imgUrls;
          for (var i = 0; i < fileUrlList.length; i++) {
            var urlOld = fileUrlList[i].url;
            if (url == urlOld) {
              fileUrlList.splice(i, 1);
              break;
            }
          }
          for (var i = 0; i < imgUrls.length; i++) {
            var urlOld = imgUrls[i].url;
            if (url == urlOld) {
              imgUrls.splice(i, 1);
              break;
            }
          }
          //移除后重新赋值
          that.setData({
            fileUrlList: fileUrlList,
            imgUrls: imgUrls,
          })
        }
        else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //返回上一页
  backPage: function () {
    wx.navigateBack({ changed: true });//返回上一页
  },

  //显示选择详情
  showUserInfo: function (e) {
    var ordernum = e.currentTarget.dataset.ordernum;
    wx.navigateTo({
      url: 'userinfo?ordernum=' + ordernum + "&oaId=" + oaId
    });

  },
  //删除选择的抄送人
  delCopyUser: function (e) {
    var that = this;
    wx.showModal({
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用删除方法了
          var userid = e.currentTarget.dataset.userid;
          var accountInfosList = that.data.accountInfosList;
          //移除抄送人
          for (var i = 0; i < accountInfosList.length; i++) {
            var id = accountInfosList[i].id;
            if (id == userid) {
              accountInfosList.splice(i, 1);//从i的位置开始向后删除1个元素
            }
          }
          that.setData({
            accountInfosList: accountInfosList
          })
        } else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  //提交保存
  bindFormSubmit: function (e) {
    var that = this;
    const params = e.detail.value;
    var list = new Array();
    list = that.data.osApprovalsList.concat(that.data.accountInfosList);
    // 传入表单数据，调用验证方法
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      util.showMsg(error.msg, "loading", "none");
      return false
    };
    wx.showLoading({
      title: "提交中...",
      mask: true
    });
    api.fetchApi2("oaProgress/saveOaApply", {
      orgid: orgid,
      userId: userId,
      userName: wx.getStorageSync('name'),
      list: list,
      params: params,
      listFile: that.data.fileUrlList,
      costId: that.data.costId
    }, "POST").then(res => {
      wx.hideLoading();
      var result = res.data;
      if (result.success) {
        util.showMsg("提交成功", "loading", "none");
        setTimeout(function () {
          wx.navigateBack({
            url: "index"
          });
        }, 1000)
      } else {
        util.showMsg(result, "loading", "none");

      }
    });
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      invoice_title: {
        required: true,
      },
      apply_price: {
        required: true,
        number: true
      }
    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      invoice_title: {
        required: '请填写发票抬头',
      },

      apply_price: {
        required: '请填写开票金额',
      }
    }

    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)

    // 自定义验证规则
    this.WxValidate.addMethod('assistance', (value, param) => {
      return this.WxValidate.optional(value) || (value.length >= 1 && value.length <= 2)
    }, '请勾选1-2个敲码助手')
  },
  //上传
  upLoad: function (e) {
    var that = this;
    var name = e.currentTarget.dataset.name;
    var conid = e.currentTarget.dataset.conid;
    var case_id = that.data.case_id;
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths; // 返回选定照片的本地ID列表，tempFilePaths可以作为img标签的src属性显示图片
        var size = tempFilePaths.length;
        for (var i = 0; i < size; i++) {
          wx.showLoading({
            title: '正在上传',
          });
          const uploadTask = wx.uploadFile({
            url: getApp().data.servsers + "/v1/api/oaProgress/saveFile",
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              'username': wx.getStorageSync('name'),
              'businessType': "发票申请",
            },
            header: {
              'token': wx.getStorageSync('token')
            },
            success: function (res) {
              var data = res.data;
              var result = JSON.parse(data);
              var fileUrlListResult = result.data;
              if (result.msg == "success") {
                wx.hideLoading();
                wx.showToast({
                  title: "上传成功",
                  icon: 'none',
                  duration: 1000
                });
                //回显图片
                var list = that.data.fileUrlList;


                list.push(fileUrlListResult);

                that.setData({
                  fileUrlList: list
                });
              } else {
                if (result.code==300){
                  wx.showToast({
                    title: result.msg,
                    icon: "none"
                  });
                  setTimeout(function () {
                    api.logout();// 退出登录
                  }, 1500);
                } else {
                  wx.showToast({
                    title: "上传失败",
                    icon: 'none',
                    duration: 1000
                  });
                }
              }
            }
          })

        }

      }
    });
  },
  //删除cost
  delCost: function (e) {
    var that = this;
    var ctype = e.currentTarget.dataset.type;
    var costid = e.currentTarget.dataset.costid;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {

        }
        else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  //显示图片
  showImg: function (option) {
    var that = this;
    var fileUrlListResult = that.data.fileUrlList;
    for (var index in fileUrlListResult) {
      that.data.imgUrls[index] = fileUrlListResult[index].url;
    }
    var url = option.currentTarget.dataset.url;
    var imgUrls = that.data.imgUrls;
    wx.previewImage({
      current: url,
      urls: imgUrls
    });
  },
  //下载(在线预览)
  downfile: function (e) {
    var that = this;
    that.setData({
      uplod: true
    })
    var url = e.currentTarget.dataset.url;
    var hz = e.currentTarget.dataset.hz;
    // getApp().data.servsers + "/case/seeEnc.shtml?case_id=" + that.data.case_id + "&hz=" + hz + "&url=" + url
    wx.showLoading({
      title: '加载中',
    })
    wx.downloadFile({
      url: url,
      success: function (res) {
        console.log(res);
        var rr = res.tempFilePath;
        wx.openDocument({
          filePath: rr,
          complete: function (res) {
            wx.hideLoading();
            that.setData({
              uplod: false
            })
          }
        })
      }
    })
    // wx.request({
    //   url: getApp().data.servsers + "/case/seeEnc.shtml", //仅为示例，并非真实的接口地址
    //   data: {
    //     case_id: that.data.case_id,
    //     hz: hz,
    //     url: url,
    //     userId: userId
    //   },
    //   header: {
    //     'content-type': 'application/json' // 默认值
    //   },
    //   success: function (res) {
    //     var newUrl = res.data;
    //     if (newUrl != "") {
    //       wx.downloadFile({
    //         url: getApp().data.fileservsers + "/miniprodownloadfile/" + "file/" + newUrl,
    //         success: function (res) {
    //           console.log(res);
    //           var rr = res.tempFilePath;
    //           wx.openDocument({
    //             filePath: rr,
    //             complete: function (res) {
    //               wx.hideLoading();
    //               that.setData({
    //                 uplod: false
    //               })
    //               wx.request({
    //                 url: getApp().data.servsers + "/case/delPath.shtml", //仅为示例，并非真实的接口地址
    //                 data: {
    //                   case_id: that.data.case_id,
    //                   newUrl: newUrl
    //                 },
    //                 header: {
    //                   'content-type': 'application/json' // 默认值
    //                 },
    //                 success: function (res) {

    //                 }
    //               })
    //             }
    //           })
    //         }
    //       })
    //     }
    //   }
    // })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //选择事件
  bindPickerChange: function (e) {
    console.log(e);
    let indexArray = this.data.index;

    indexArray[parseInt(e.currentTarget.dataset.id)] = e.detail.value;
    this.setData({
      index: indexArray
    });
  },
  //用户选择
  userinfo: function (e) {
    var that = this;
    var proId = e.currentTarget.dataset.proid;
    var appointType = e.currentTarget.dataset.appointtype;//指定类型 role 指定角色 user 指定人员
    var roleKey = e.currentTarget.dataset.rolekey;//角色key
    var examinealltype = e.currentTarget.dataset.examinealltype;//是否需要全部同意才通过 是:0  否:1
    var searchusertype = e.currentTarget.dataset.searchusertype;//copy查询抄送人 examine查询审核人
    var processType = that.data.examineType;
    var choiceuser = e.currentTarget.dataset.choiceuser;
    wx.navigateTo({
      url: 'userinfo?proId=' + proId + "&appointType=" + appointType + "&processType=" + processType + "&roleKey=" + roleKey + "&examinealltype=" + examinealltype + "&searchusertype=" + searchusertype + "&choiceuser=" + choiceuser
    });
  },
})